package org.merka.cryptochat.servlet;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ServerEndpoint("/ws")
public class ConversationWebSocketEndpoint
{
	private static transient Logger logger = LoggerFactory.getLogger(ConversationWebSocketEndpoint.class);
	
	@OnOpen
	public void onOpen()
	{
		logger.info("Websocket open.");
	}
	
	@OnClose
	public void onClose()
	{
		logger.info("Websocket closed.");
	}
	
	@OnMessage(maxMessageSize = 2048L)
	public void onMessage(Session session, String message, boolean last)
	{
		if( session.isOpen() )
		{
			logger.info("\n\n\nMessage received:  " + message + "\n\n\n");
			try
			{	
				session.getBasicRemote().sendText(message + " [echo]", last);
			}
			catch(IOException ioe)
			{
				try
				{
					session.close();
				}
				catch(Exception ex)
				{
					session = null;
				}
			}
		}
	}
}
